/**
 * Created by Administrator on 2015/1/23.
 */
var AutoReply = (function(){
	var XHR = {
		/**
		 * ajax取已添加的关键字列表
		 * @param hash
		 * @param config
		 * @returns {boolean}
		 */
		getKeywordList : function(hash,config){
			if(!hash){
				console && console.log("缺省hash");
				return false;
			}
			var fn = WXB.FN;
			var config = config || {};
			var loading = config.loading || fn;
			var removeLoading = config.removeLoading || fn;
			var success = config.success || fn;
			var empty = config.empty || fn;
			var timeout = config.timeout || fn;
			var error = config.error || fn;
			$.ajax({
				url : WXB.URLS.api,
				type : "GET",
				dataType : "JSON",
				data : { action:"GetKeyWord", hash:hash},
				timeout : WXB.AJAX_TIMEOUT,
				beforeSend : function(){
					loading();
				},
				success : function(res){
					removeLoading();
					var status = res.status;
					var list = res.lists;
					if(status == "ok" && list && list.length == 0){
						empty();
					}else if(status == "ok" && list && list.length > 0){
						success(res);
					}
				},
				error : function(xhr,txt){
					removeLoading();
					if(txt == "timeout"){
						timeout();
					}else{
						error();
					}
				}
			})
		},
		/**
		 * 修改某个关键字回复或删除某个关键字回复
		 * @param config
		 */
		ajaxSetKeyword : function(hash,config){
			var fn = WXB.FN;
			var config = config || {};
			var id = config.id;
			var keyword = config.keyword;
			var response = config.response;
			var loading = config.loading || fn;
			var removeLoading = config.removeLoading || fn;
			var success = config.success || fn;
			var fail = config.fail || fn;
			var timeout = config.timeout || fn;
			var error = config.error || fn;
			var action = "";
			var data = {};
			if(id && !keyword && !response){ //删除
				action = "RemoveKewWord";
			}
			if(!id && keyword && response){ //修改
				action = "SetKeyWord";
			}
			data["hash"] = hash;
			data["action"] = action;
			if(id) data["id"] = id;
			if(keyword) data["keyword"] = keyword;
			if(response) data["response"] = response;
			$.ajax({
				url : WXB.URLS.api,
				type : "POST",
				dataType : "JSON",
				data : data,
				beforeSend : function(){
					loading();
				},
				success : function(res){
					removeLoading();
					if(res && res.status == "ok"){
						success(res);
					}else if(res && res.status == "fail"){
						fail(res);
					}else{
						error()
					}
				},
				error : function(xhr,txt){
					removeLoading();
					if(txt == "timeout"){
						timeout();
					}else{
						error();
					}
				}
			})
		}
	}
	function init(){
		$("#tabNavWrap").on("click",".tabNavItem",function(e){
			var target = $(e.currentTarget);
			var tab = target.attr("data-tab");
			target.addClass("active").siblings().removeClass("active");
			$("#tabConWrap").children().hide().filter(function(){
				return $(this).attr("data-tab") == tab;
			}).show();
			$("#keywordInp").val("").removeAttr("readOnly");
			$("#replyTextarea").val("").removeAttr("readOnly");;

			return false;
		})
		$("#tabNavWrap").children(":first").trigger("click");
		$("#current_account_name").text(WXB.G.SwitchAccount.getName());
		$("#replyList").on("click","#creatkeywordWhenEmpty",function(e){ //当列表为空时点击创建按钮
			$("#tabNavWrap").children(".addKeyword").trigger("click");
		});
		$("#replyList").on("click","#refreshWhenTimeout,#refreshWhenError",function(e){ //当请求更表超时或失败
			getKeywordList();
		});
		$("#replyList").on("click",".editBtn",function(e){ //进入编辑
			var target = $(e.currentTarget);
			var keyword = target.attr("data-keyword");
			var response = target.attr("data-response");
			$("#tabNavWrap").children(".addKeyword").trigger("click");
			$("#keywordInp").val(keyword).attr("readOnly",true);
			$("#replyTextarea").val(response);
			return false;
		});
		//删除某个关键字
		$("#replyList").on("click",".removeBtn",function(e){ //删除
			var result = window.confirm("确认要删除该关键字回复吗？");
			if(result){
				var target = $(e.currentTarget);
				var id = target.attr("data-replyid");
				if(id) removeKeyword(id);
			}
			return false;
		});
		//修改或创建某个关键字
		$("#submitMenuDataBtn").on("click",function(e){
			var keyword = $("#keywordInp").val();
			var response = $("#replyTextarea").val();
			if(keyword && response){
				editKeywrod(keyword,response);
			}
			return false;
		});

		WXB.G.SwitchAccount.on("change",function(data){
			$("#current_account_name").text(data.name);
			getKeywordList();
		})
		getKeywordList();
	}

	/**
	 * 依据不同公众号hash获取该帐号下的关键字回复列表
	 */
	function getKeywordList(){
		var hash = WXB.G.SwitchAccount.getHash();
		XHR.getKeywordList(hash,{
			loading : function(){
				var listUl = $("#replyList");
				var loading = '<li class="loading" style="height:200px; line-height:200px; text-align:center; font-size:14px;"><i class="fa fa-spinner fa-spin"></i>正在加载关键字回复列表</li>';
				listUl.html(loading);
			},
			removeLoading : function(){
				$("#replyList").html("");
			},
			success : function(res){
				var list = res.lists;
                var html = "";
				for(var i in list){
					var d = list[i];
					var keyword = d["keyword"];
					var response = d["response"];
					var id = d["id"];
					var create_time = d["create_time"];
					html += '<li class="replyItem">'
					html += '<div class="panel panel-default">';
					html += '<div class="panel-heading">关键字：<strong>'+keyword+'</strong></div>';
					html += '<div class="panel-body">'+response+'</div>';
					html += '<div class="panel-footer clearfix">';
					html += '  <div class="btn-group pull-right">';
					html += '       <a class="btn btn-default btn-sm editBtn" href="javascript:; data-replyid="'+id+'" data-keyword="'+keyword+'" data-response="'+response+'" data-createtime="'+create_time+'"><i class="fa fa-edit"></i> 编辑</a>';
					html += '       <a class="btn btn-default btn-sm removeBtn" href="javascript:;" data-replyid="'+id+'" data-keyword="'+keyword+'" data-response="'+response+'" data-createtime="'+create_time+'"><i class="fa fa-times"></i> 删除</a>';
					html += '  </div>';
					html += '</div>';
					html += '</div>';
					html += '</li>';
				}
				$("#replyList").html(html);
			},
			empty : function(){
				var html = '<div style="height:100%; line-height:150px; width:100%; text-align:center">此帐号还未添加任何关键字回复，<span id="creatkeywordWhenEmpty" class="creatkeywordWhenEmpty btn btn-primary"><i class="fa fa-plus"></i> 去创建</span></div>'
				$("#replyList").html(html);
			},
			timeout : function(){
				console && console.log("请求关键字列表时超时");
				var html = '<div style="height:100%; line-height:150px; width:100%; text-align:center">请求超时，<span id="refreshWhenTimeout" class="creatkeywordWhenEmpty btn btn-primary">重试</span></div>'
				$("#replyList").html(html);
			},
			error : function(){
				console && console.log("请求关键字列表时服务端出错");
				var html = '<div style="height:100%; line-height:150px; width:100%; text-align:center">请求失败，<span id="refreshWhenError" class="creatkeywordWhenEmpty btn btn-primary">重试</span></div>'
				$("#replyList").html(html);
			}
		})
	}

	/**
	 * 修改某个关键字回复 包括编辑跟创建
	 */
	function editKeywrod(keyword,response){
		if(!response){
			alert("回复文字不能为空");
			return false;
		}
		var hash = WXB.G.SwitchAccount.getHash();
		var menuLoadingLayer = $("#menuLoadingLayer");
		if(!keyword || !response || !hash) return false;
		XHR.ajaxSetKeyword(hash,{
			keyword : keyword,
			response : response,
			loading : function(){ menuLoadingLayer.show()},
			removeLoading : function(){ menuLoadingLayer.hide();},
			success : function(res){
				getKeywordList();
				WXB.G.Alert("success",'<p style="wdith:160px">保存成功！</p>');
			},
			fail : function(res){
				alert(res.msg)
			},
			timeout : function(){
				alert("请求超时请稍后重试")
			},
			error : function(){
				alert("请求出错请稍后重试")
			}
		})
	}

	/**
	 * 删除某个关键字
	 * @param id
	 * @returns {boolean}
	 */
	function removeKeyword(id){
		var hash = WXB.G.SwitchAccount.getHash();
		if(!id || !hash) return false;
		var menuLoadingLayer = $("#menuLoadingLayer");
		XHR.ajaxSetKeyword(hash,{
			id : id,
			loading : function(){ menuLoadingLayer.show()},
			removeLoading : function(){ menuLoadingLayer.hide();},
			success : function(res){
				WXB.G.Alert("success",'<p style="wdith:160px">删除成功！</p>');
				$("#replyList").find(".removeBtn").filter(function(){
					return $(this).attr("data-replyid") == id;
				}).parents(".replyItem").remove();
			},
			fail : function(res){
				alert(res.msg);
			},
			timeout : function(){},
			error : function(){}
		})
	}

	return{
		init : init
	}

})();
$(function(){
	WXB.G.SwitchAccount.init(function(){
		AutoReply.init();
	});
})
